
package com.googlecode.mgwt.examples.showcase.client.activities;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.googlecode.mgwt.examples.showcase.client.AppController;
import com.googlecode.mgwt.examples.showcase.client.ClientFactory;
import com.googlecode.mgwt.examples.showcase.client.activities.elements.WaterCountView;
import com.googlecode.mgwt.examples.showcase.client.places.WaterCountPlace;
import com.googlecode.mgwt.examples.showcase.client.rpc.AppAsyncCallback;
import com.googlecode.mgwt.examples.showcase.shared.ServiceCallDTO;
import com.googlecode.mgwt.mvp.client.MGWTAbstractActivity;


public class WaterCountActivity extends MGWTAbstractActivity {

	private final ClientFactory clientFactory;
	private WaterCountPlace place;

	private List<ServiceCallItem> items;

	public WaterCountActivity(ClientFactory clientFactory, WaterCountPlace place) {
		this.clientFactory = clientFactory;
		this.place = place;

	}

	@Override
	public void start(AcceptsOneWidget panel, final EventBus eventBus) {
		final WaterCountView view = clientFactory.getWaterCountView();
//
//		view.setBackButtonText(clientFactory.getUserProfile().getCurrentUser().getLabels().back());
//		view.setTitle(clientFactory.getUserProfile().getCurrentUser().getLabels().callsList());
//
//		view.reset();
//		addHandlerRegistration(view.getBackButton().addTapHandler(new TapHandler() {
//
//			@Override
//			public void onTap(TapEvent event) {ActionEvent.fire(eventBus, ActionNames.BACK);
//
//			}
//		}));
//		
//
//		addHandlerRegistration(view.getList().addCellSelectedHandler(new CellSelectedHandler() {
//
//			@Override
//			public void onCellSelected(CellSelectedEvent event) {
//				final int index = event.getIndex();
//				AnimationSelectedEvent.fire(eventBus, new Animation(AnimationNames.TEC_DETAILS, "Flip",items.get(index).getServiceCall()));
//
//			}
//		}));

		panel.setWidget(view);
		loadCalls();
	}
	
	private void loadCalls(){
		clientFactory.getService().getAllCalls(AppController.getClientFactory().getUserProfile().getCurrentUser().ordinal(),
				new AppAsyncCallback<List<ServiceCallDTO>>() {

			@Override
			public void onInnerSuccess(List<ServiceCallDTO> aResult) {
				final TecView view = clientFactory.getUIView();
				items = createItems(aResult);
				view.renderItems(items);
				
			}
		});
	}

	/**
	 * @return
	 */
	private List<ServiceCallItem> createItems(List<ServiceCallDTO> callList) {
		ArrayList<ServiceCallItem> list = new ArrayList<ServiceCallItem>();
		for (ServiceCallDTO call : callList) {
			list.add(new ServiceCallItem(call));
		}
		
		return list;
	}

}
